/*
 * Copyright (C) 2012 Matt Broadstone
 * Contact: http://code.google.com/p/qconnman/
 *
 * This file is part of the QConnman Library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

#include <QMetaProperty>
#include <QMetaObject>
#include <QDBusMetaType>
#include <QDebug>

#include "connmanobject.h"

ConnManObject::ConnManObject(QObject *parent)
    : QObject(parent)
{
}

ConnManObject::~ConnManObject()
{
}

void ConnManObject::propertyChanged(const QString &property, const QDBusVariant &value)
{
    QString modProperty(property);
    if (modProperty.contains("."))
        modProperty.remove(".");

    qDebug() << Q_FUNC_INFO << modProperty << " = " << value.variant();
    setObjectProperty(this, modProperty, value.variant());
}

void ConnManObject::setObjectProperty(QObject *object, const QString &property, const QVariant &value)
{
    const QMetaObject *mo = object->metaObject();
    int idx = mo->indexOfProperty(property.toLatin1());
    if (idx == -1) {
        qDebug() << "\tinvalid property: " << property;
        return;
    }

    if (mo->property(idx).type() == QMetaType::QObjectStar) {
        QObject *childObject = qvariant_cast<QObject*>(object->property(property.toLatin1()));
        if (!childObject) {
            qDebug() << "\tcould not extract child qobject for property: " << property.toLatin1();
        } else {
            QVariantMap data = qdbus_cast<QVariantMap>(value);
            foreach (QString dataProperty, data.keys())
                setObjectProperty(childObject, dataProperty, data.value(dataProperty));
        }
    } else {
        if (!mo->property(idx).write(object, value))
            qDebug() << "\tcould not write property data: " << value;
        else
            qDebug() << "\twrote property(" << property << ") = " << value;
    }
}

